package com.fsj.admin.common.task;

import com.fsj.admin.common.domain.DictDO;
import com.fsj.admin.common.domain.DictTaskDO;
import com.fsj.admin.common.service.DictService;
import com.fsj.admin.common.service.DictTaskService;
import com.fsj.admin.common.utils.TimeUtils;
import com.fsj.admin.system.service.OrderService;
import org.apache.shiro.crypto.hash.Hash;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Component
public class SysTask {
    @Autowired
    private DictTaskService dictTaskService;
    @Autowired
    private DictService dictService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    /**
     * 更新订单配置
     * 每天00点执行
     *
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void fixedDelayJob() throws InterruptedException {
        Map<String, Object> params = new HashMap<>(1);
        params.put("status", "0");
        List<DictTaskDO> list = dictTaskService.list(params);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            DictTaskDO taskDO = list.get(i);
            threadPoolTaskExecutor.execute(new Runnable() {
                public void run() {
                    DictDO dictDO = dictService.get(taskDO.getDictId());
                    if (dictDO != null) {
                        dictDO.setValue(taskDO.getDictValue());
                        int update = dictService.update(dictDO);
                        if (update > 0) {
                            taskDO.setStatus("1");
                            dictTaskService.update(taskDO);
                        }
                    }
                }
            });
        }
    }

    /**
     * 关闭超过10分钟订单
     *
     * @throws InterruptedException
     */
//    @Scheduled(cron = "0/1 * * * * ?")
    @Scheduled(cron = "0 0/1 * * * ?")
    public void colseOrder() throws InterruptedException {
        // 得到当前时间的前10分钟时间
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MINUTE, -10);
        Date time = cal.getTime();
        orderService.colseOrder(time);
    }

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MINUTE, -10);
        System.out.println(cal.getTime());
    }
}
